package com.ry.novel.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ry.novel.bean.UserHolder;
import com.ry.novel.enums.NovelConst;
import com.ry.novel.enums.ResponseStatus;
import com.ry.novel.exception.BusinessException;
import com.ry.novel.model.dto.UserInfo;
import com.ry.novel.model.resp.Result;
import com.ry.novel.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;

/**
 * @author ry
 * @since 2022-01-25 09:49
 **/
@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        UserInfo userInfo = jwtTokenUtil.getUserInfoFromToken(token);
        if (userInfo == null){
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding("utf8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.fail(ResponseStatus.No_LOGIN)));

            return false;
        }
        if (userInfo.getState().equals(NovelConst.ACCOUNT_STATE_FORBIDDEN)){
            response.setContentType("application/json");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setCharacterEncoding("utf8");
            response.getWriter().write(new ObjectMapper().writeValueAsString(Result.fail(ResponseStatus.USER_STATE_FORBIDDEN)));

            return false;
        }
        UserHolder.userInfo.set(userInfo);
        return true;

    }
}